<template>
  <div class="p-6 space-y-6">
    <!-- 社团概览 -->
    <Overview title="社团详情" description="查看社团基本信息及相关操作" />

    <!-- 社团信息 -->
    <el-card shadow="hover">
      <el-descriptions title="社团信息" :column="2" border>
        <el-descriptions-item label="社团名称">{{ club.name }}</el-descriptions-item>
        <el-descriptions-item label="社团简介">{{ club.descr }}</el-descriptions-item>
      </el-descriptions>
      <el-button type="primary" @click="handleEdit" style="margin-top: 20px" :disabled="user.role !== 'PRE'">修改社团简介</el-button>
    </el-card>

    <!-- 社团图片 -->
    <el-card shadow="never" class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="text-lg font-medium">社团图片</h3>
          <el-upload
              v-if="user.role === 'ADM' || user.role === 'PRE'"
              class="upload-demo"
              action="http://localhost:8080/files/wang/upload"
              :on-success="handleUploadSuccess"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :data="{ clubId: clubId, uploaderId: user?.id }"
          >
            <el-button type="primary" size="small">上传图片</el-button>
          </el-upload>
        </div>
      </template>

      <div v-if="images.length === 0" class="text-center text-gray-500 py-4">
        暂无图片，请上传
      </div>
      
      <div v-else class="grid grid-cols-6 gap-2">
        <div v-for="image in images" :key="image.id" 
             class="relative group rounded-lg overflow-hidden border border-gray-200 hover:shadow-lg transition-all duration-300">
          <img :src="image.imageUrl" 
               alt="社团图片" 
               class="w-full h-24 object-cover" />
          <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-all duration-300">
            <div class="absolute bottom-0 left-0 right-0 p-1 text-white text-xs opacity-0 group-hover:opacity-100 transition-opacity duration-300">
              <p class="mb-0.5 truncate">上传时间：{{ formatDate(image.uploadTime) }}</p>
              <p class="truncate">上传人：{{ image.uploaderName }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 评论区 -->
    <el-card shadow="always" header="评论区">
      <QuillEditor 
        v-model="editorContent" 
        :clubId="clubId" 
        :uploaderId="user?.id"
        style="margin-bottom: 15px;" 
      />
      <el-button class="mt-4" type="primary" @click="submitComment">发送评论</el-button>

      <div class="mt-6">
        <h4>评论列表：</h4>
        <el-timeline>
          <el-timeline-item v-for="(c, i) in comments" :key="i" :timestamp="formatDate(c.createTime)">
            <div class="flex items-start gap-3">
              <div class="flex-1">
                <div class="text-sm text-gray-500 mb-1">
                  <span class="font-medium text-gray-700">{{ c.studentName }}</span>
                  评论：
                </div>
                <div class="text-gray-800 comment-content" v-html="c.content"></div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
  <el-dialog v-model="data.formVisible" width="500px">
    <el-form :model="data.form" label-width="100px" ref="formRef">
    <el-form-item label="社团简介" prop="descr">
      <el-input v-model="data.form.descr" type="textarea" placeholder="请输入社团简介"></el-input>
    </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

import Overview from '@/views/Overview.vue';
import QuillEditor from '@/components/QuillEditor.vue';


const data = reactive({
  formVisible: false,
  form:{
    descr:''
  }

})

const route = useRoute();
let clubId = route.query.clubId;
const user = JSON.parse(localStorage.getItem('xm-pro-user'));

const club = ref({});
const images = ref([]);
const comments = ref([]);
const editorContent = ref('');


// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  return new Date(date).toLocaleString();
};



// 获取社团信息
const fetchClub = async () => {
  if (!clubId) {
    clubId = user.clubId;
  }


  try {
    const {data} = await axios.get(`http://localhost:8080/club/selectById/${clubId}`);
    club.value = data.data;
    // 获取社团图片列表
    const imageRes = await axios.get(`http://localhost:8080/club/image/list/${clubId}`);
    images.value = imageRes.data.data;
    // 获取评论列表
    const commentRes = await axios.get(`http://localhost:8080/club/comment/list/${clubId}`);
    comments.value = commentRes.data.data;
    console.log('获取到的评论数据:', comments.value);
  } catch (err) {
    ElMessage.error('获取社团信息失败');
  }
};
const handleEdit = () => {
  fetchClub(); // 获取社团信息并填充到表单
  data.formVisible = true
}

//提交修改
const save = async () => {
  try {
    const response = await axios.put(`http://localhost:8080/club/updateById`, {
      id: data.form.id,
      name:data.form.name,
      descr: data.form.descr
    });
    ElMessage.success('修改成功');
    data.formVisible = false;
    club.value.descr = data.form.descr; // 更新本地社团信息
  } catch (error) {
    ElMessage.error('修改失败');
    console.error(error);
  }
};


onMounted(() => {
  fetchClub(); // 在页面加载时获取社团信息
});

// 上传成功
const handleUploadSuccess = async (res) => {
  console.log("上传成功返回的数据：", res);
  if (res.errno === 0 && res.data && Array.isArray(res.data) && res.data.length > 0 && res.data[0].url) {
    try {
      ElMessage.success("图片上传成功");
      // 重新获取图片列表
      const imageRes = await axios.get(`http://localhost:8080/club/image/list/${clubId}`);
      images.value = imageRes.data.data;
    } catch (err) {
      ElMessage.error("保存图片失败");
    }
  } else {
    ElMessage.error("上传成功，但未获取到有效的图片 URL");
  }
};

// 文件上传前的校验
const beforeUpload = (file) => {
  const maxSize = 10 * 1024 * 1024; // 10 MB
  if (file.size > maxSize) {
    ElMessage.error("文件大小不能超过 10 MB");
    return false;
  }
  return true;
};

// 提交评论
const submitComment = async () => {
  if (!editorContent.value) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  try {
    // 提取评论中的图片URL
    const imgRegex = /<img[^>]+src="([^">]+)"/g;
    const imgUrls = [];
    let match;
    while ((match = imgRegex.exec(editorContent.value)) !== null) {
      imgUrls.push(match[1]);
    }
    
    console.log('编辑器内容:', editorContent.value);
    console.log('提取的图片URL:', imgUrls);
    
    const comment = {
      clubId: clubId,
      studentId: user.id,
      content: editorContent.value,
      images: imgUrls.length > 0 ? imgUrls.join(',') : null // 如果没有图片，设置为 null
    };
    
    console.log('准备提交的评论数据:', comment);
    
    const response = await axios.post('http://localhost:8080/club/comment/add', comment);
    console.log('评论提交响应:', response.data);
    
    if (response.data.code === '200') {
      ElMessage.success("评论成功");
      editorContent.value = '';
      // 重新获取评论列表
      const commentRes = await axios.get(`http://localhost:8080/club/comment/list/${clubId}`);
      comments.value = commentRes.data.data;
      console.log('更新后的评论数据:', comments.value);
    } else {
      throw new Error(response.data.msg || '评论失败');
    }
  } catch (err) {
    console.error('评论提交失败:', err);
    ElMessage.error(err.message || "评论失败");
  }
};

// 加入社团
const handleJoin = async (row) => {
  try {
    await ElMessageBox.confirm('确定要加入该社团吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    const res = await axios.post('http://localhost:8080/club/join', {
      clubId: row.id,
      studentId: user.id
    })
    
    if (res.data.code === '200') {
      ElMessage.success('申请已提交，请等待审核')
      // 重新获取所有数据
      await Promise.all([
        fetchClub(),
        loadData()
      ])
    } else {
      ElMessage.error(res.data.msg || '申请失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('申请失败')
    }
  }
}

// 获取社团列表
const loadData = async () => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/club/selectAll')
    if (res.data.code === '200') {
      // 获取用户已加入的社团列表
      const joinedRes = await axios.get(`http://localhost:8080/club/selectByStudentId/${user.id}`)
      const joinedClubs = joinedRes.data.data || []
      const joinedClubIds = new Set(joinedClubs.map(club => club.id))
      
      // 更新社团列表，添加加入状态
      tableData.value = res.data.data.map(club => ({
        ...club,
        isJoined: joinedClubIds.has(club.id)
      }))
    } else {
      ElMessage.error(res.data.msg || '获取社团列表失败')
    }
  } catch (err) {
    ElMessage.error('获取社团列表失败')
    console.error(err)
  } finally {
    loading.value = false
  }
}

const getImageUrl = (content) => {
  const match = content.match(/<img[^>]+src="([^">]+)"/);
  return match ? match[1] : '';
};

onMounted(() => {
  fetchClub();
});
</script>

<style scoped>
.upload-demo {
  display: inline-block;
}

.el-card {
  margin-bottom: 1.5rem;
}

.el-card :deep(.el-card__header) {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #ebeef5;
}

.el-card :deep(.el-card__body) {
  padding: 1.5rem;
}

.grid {
  margin: 0 -0.5rem;
}

.grid > div {
  padding: 0.5rem;
}

.comment-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 10px 0;
  border-radius: 4px;
}

.comment-content :deep(p) {
  margin: 0;
  line-height: 1.5;
}
</style>